﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MySQL.Db
{
    public class ConnectionWithTransaction : IDisposable
    {
        private MySqlConnection connection;
        private MySqlTransaction transaction;
		bool disposed = false;

        public ConnectionWithTransaction(string connectionString)
        {
            this.connection = new MySqlConnection(connectionString);

            this.Open();

            this.transaction = this.connection.BeginTransaction();
        }

        public void Open()
        {
            this.connection.Open();
        }

        private void Close()
        {
			if (this.connection.State != System.Data.ConnectionState.Closed)
			{
				this.connection.Close();
				this.connection.Dispose();
			}

			if (this.transaction != null)
				this.transaction.Dispose();
        }

        public void Commit()
        {
            this.transaction.Commit();
        }

        public void Rollback()
        {
            this.transaction.Rollback();
        }

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposed)
				return;

			if (disposing == true)
			{
				this.Close();
			}

			disposed = true;
		}

		~ConnectionWithTransaction()
		{
			Dispose(false);
		}

        public MySqlConnection Connection
        {
            get { return this.connection; }
        }

        public MySqlTransaction Transaction
        {
            get { return this.transaction; }
        }
    }
}
